const AuthStepType = {
  ONE: 1,
  TWO: 2,
  THREE: 3,
};

Component({
  options: {
    multipleSlots: true,
  },
  properties: {
    currAuthStep: {
      type: Number,
      value: AuthStepType.ONE,
    },
    userInfo: {
      type: Object,
      value: {},
    },
    isNeedGetUserInfo: {
      type: Boolean,
      value: false,
    },
  },
  data: {
    defaultAvatarUrl: 'https://tdesign.gtimg.com/miniprogram/template/retail/usercenter/icon-user-center-avatar@2x.png',
    AuthStepType,
    userInfo: {
      avatarUrl: '',
      nickName: '未登录'
    },
    orderCounts: {
      unpaid: 0,
      unshipped: 0,
      unreceived: 0,
      afterSale: 0
    }
  },
  methods: {
    gotoUserEditPage() {
      this.triggerEvent('gotoUserEditPage');
    },
    onLoad: function() {
      this.loadUserInfo();
      this.loadOrderCounts();
    },
    onShow: function() {
      this.loadOrderCounts();
    },
    loadUserInfo: function() {
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        this.setData({
          userInfo: userInfo
        });
      }
    },
    handleLogin: function() {
      // 检查是否已经登录
      const currentUserInfo = wx.getStorageSync('userInfo');
      if (currentUserInfo && currentUserInfo.nickName && currentUserInfo.avatarUrl) {
        wx.showToast({
          title: '已登录',
          icon: 'success'
        });
        return;
      }

      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
          console.log('获取用户信息成功', res);
          const userInfo = res.userInfo;
          
          // 显示加载提示
          wx.showLoading({
            title: '登录中...',
            mask: true
          });
          
          // 调用云函数login存储用户信息
          wx.cloud.callFunction({
            name: 'login',
            data: {
              nickname: userInfo.nickName,
              avatar: userInfo.avatarUrl
            },
            success: loginRes => {
              wx.hideLoading();
              console.log('云函数登录成功', loginRes);
              
              // 将openid等信息存入userInfo
              userInfo.openid = loginRes.result.openid;
              wx.setStorageSync('userInfo', userInfo);
              
              // 更新页面数据
              this.setData({ 
                userInfo: userInfo 
              });
              
              // 重新加载订单数量
              this.loadOrderCounts();
              
              wx.showToast({
                title: '登录成功',
                icon: 'success'
              });
            },
            fail: err => {
              wx.hideLoading();
              console.error('云函数登录失败', err);
              wx.showToast({
                title: '登录失败',
                icon: 'error'
              });
            }
          });
        },
        fail: (err) => {
          console.log('获取用户信息失败', err);
          if (err.errMsg && err.errMsg.includes('cancel')) {
            wx.showToast({
              title: '用户取消授权',
              icon: 'none'
            });
          } else {
            wx.showToast({
              title: '获取用户信息失败',
              icon: 'error'
            });
          }
        }
      });
    },
    loadOrderCounts: function() {
      const userInfo = wx.getStorageSync('userInfo');
      if (!userInfo || !userInfo.openid) {
        this.setData({
          orderCounts: {
            unpaid: 0,
            unshipped: 0,
            unreceived: 0,
            afterSale: 0
          }
        });
        return;
      }
      wx.cloud.callFunction({
        name: 'orderCounts',
        data: { openid: userInfo.openid },
        success: res => {
          this.setData({
            orderCounts: res.result || {
              unpaid: 0,
              unshipped: 0,
              unreceived: 0,
              afterSale: 0
            }
          });
        }
      });
    },
    navigateToOrders: function(e) {
      const type = e.currentTarget.dataset.type;
      // tabIndex: 0全部 1待付款 2待发货 3待收货
      let tabIndex = 0;
      if (type === 'unpaid') tabIndex = 1;
      else if (type === 'unshipped') tabIndex = 2;
      else if (type === 'unreceived') tabIndex = 3;
      wx.navigateTo({
        url: `/pages/order/order?tab=${tabIndex}`
      });
    },
    navigateToAllOrders: function() {
      wx.navigateTo({
        url: '/pages/order/order'
      });
    },
    navigateToAddress: function() {
      wx.navigateTo({
        url: '/pages/address/address'
      });
    },
    navigateToFavorites: function() {
      wx.navigateTo({
        url: '/pages/favorites/favorites'
      });
    },
    contactService: function() {
      wx.showModal({
        title: '联系客服',
        content: '客服电话：400-xxx-xxxx',
        showCancel: false
      });
    }
  },
});
